import axios from 'axios'

// 使用相对路径，通过vite代理转发到后端
const API_BASE_URL = '/api'

const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  withCredentials: false,
  headers: {
    'Content-Type': 'application/json'
  }
})

export interface FileItem {
  name: string
  path: string
  type: 'file' | 'folder'
  size: number
  modified: string
  mimeType?: string
}

export interface FileListResponse {
  success: boolean
  data: {
    path: string
    files: FileItem[]
  }
}

export interface ApiResponse {
  success: boolean
  message: string
  data?: any
}

// 获取文件列表
export const getFiles = async (path = ''): Promise<FileListResponse> => {
  const response = await apiClient.get('/files', {
    params: { path }
  })
  return response.data
}

// 创建文件夹
export const createFolder = async (name: string, path = ''): Promise<ApiResponse> => {
  const response = await apiClient.post('/folder', { name, path })
  return response.data
}

// 上传文件
export const uploadFiles = async (
  files: File[], 
  path = '', 
  onProgress?: (progress: number) => void
): Promise<ApiResponse> => {
  const formData = new FormData()
  files.forEach(file => {
    formData.append('files', file)
  })
  
  const response = await apiClient.post('/upload', formData, {
    params: { path },
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    onUploadProgress: (progressEvent) => {
      if (progressEvent.total && onProgress) {
        const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        onProgress(percentCompleted)
      }
    }
  })
  return response.data
}

// 删除文件或文件夹
export const deleteFiles = async (paths: string[]): Promise<ApiResponse> => {
  const response = await apiClient.delete('/files', {
    data: { paths }
  })
  return response.data
}

// 下载文件
export const downloadFile = (path: string): string => {
  return `${API_BASE_URL}/download?path=${encodeURIComponent(path)}`
}

// 移动/重命名文件
export const moveFile = async (from: string, to: string): Promise<ApiResponse> => {
  const response = await apiClient.put('/move', { from, to })
  return response.data
}

// 获取文件信息
export const getFileInfo = async (path: string): Promise<ApiResponse> => {
  const response = await apiClient.get('/info', {
    params: { path }
  })
  return response.data
}

// 错误处理拦截器
apiClient.interceptors.response.use(
  response => response,
  error => {
    console.error('API Error:', error.response?.data || error.message)
    return Promise.reject(error)
  }
) 